/**
 * @Title: MatchFingerprintSyncLogin.java
 * @Package: com.jason.fingerprint.logic
 * @Descripton: TODO
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年12月30日 下午10:12:58
 * @Version: V1.0
 */
package com.jason.fingerprint.logic;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.fgtit.fpcore.FPMatch;
import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.beans.ui.FingerPrintBean;
import com.jason.fingerprint.common.UIHelper;
import com.jason.fingerprint.utils.CodecUtils;

import org.kymjs.aframe.database.KJDB;
import org.kymjs.aframe.utils.StringUtils;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android_serialport_api.AsyncFingerprint;
import android_serialport_api.SerialPortManager;

/**
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年12月30日 下午10:12:58
 */
@SuppressLint("LongLogTag")
public class MatchFingerprintSyncLogic {

	private static final String TAG = "MatchFingerprintSyncLogic";
	public static final String SIGNIN_TYPE = "finger_type";
	public static final int SIGNIN_TYPE_FINGER = 0;
	public static final int SIGNIN_TYPE_CARD = 2;

	public boolean mIsCallBack = true;// 是否有回调，此需要Handle
	public boolean mIsShowImage = false;// 是否显示图像
	public boolean mIsManager = false;// 判断是否是管理员,默认false--矫正人员，
	public boolean mIsDestory = false;//
	public Context mContext;
	public String mImei;
	public KJDB mKjdb;
	private Message mMessage;
	private AsyncFingerprint mValidateFingerprint;
	private Handler mHandler;

	private List<FingerPrintBean> mFingerBeans;//获取所有的指纹信息

	public MatchFingerprintSyncLogic(Context context){
		initSerialPort(context);
	}


	private void initSerialPort(Context context) {
		this.mContext = context;
		try {
			if (!SerialPortManager.getInstance().isOpen()) {
				int code = FPMatch.getInstance().InitMatch(1, "http://www.hfcctv.com/");
				if (code == 0) {
					android.util.Log.i(TAG, "Init Match Error");
				} else {
					android.util.Log.i(TAG, "Init Match Success");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			android.util.Log.e(TAG, "Init Match Error", e);
		}
		this.mImei = AppContext.getInstance().getImei();
		this.mKjdb = AppContext.getInstance().getKjdb();
		mMessage = new Message();
	}

	// 初始化监听
	private void initListener() {
		mValidateFingerprint = SerialPortManager.getInstance().getNewAsyncFingerprint();
		if (!SerialPortManager.getInstance().isOpen()) {
			Log.i(TAG, "Open Error ");
			mMessage.what = UIHelper.FINGERPRINT_FAIL;
			send();
			return;
		} else {
			android.util.Log.i(TAG, "is Open: ");
		}
		if (AppContext.getInstance().is3GEquipment()){
			mValidateFingerprint.setOnGetImageListener(new AsyncFingerprint.OnGetImageListener() {
				@Override
				public void onGetImageSuccess() {
					Log.i(TAG,
							"---->setOnGetImageListener onGetImageSuccess 001");
					if (mIsShowImage) {
						mValidateFingerprint.FP_UpImage();//
						Log.i(TAG,
								"---->setOnGetImageListener onGetImageExSuccess 008");
					} else {
						mValidateFingerprint.FP_GenChar(1);
						Log.i(TAG,
								"---->setOnGetImageListener onGetImageSuccess 009");
					}
				}

				@Override
				public void onGetImageFail() {
					Log.i(TAG,
							"---->setOnGetImageListener onGetImageFail 002");
					if (!mIsDestory) {
						mValidateFingerprint.FP_GetImage();
					}
				}
			});

			mValidateFingerprint.setOnUpImageListener(new AsyncFingerprint.OnUpImageListener() {
				@Override
				public void onUpImageSuccess(byte[] data) {
					Log.i(TAG,
							"---->setOnUpImageListener onUpImageSuccess 010");
					Log.i(TAG, "---->setOnUpImageListener up image data.length="
							+ data.length);
					mValidateFingerprint.FP_GenChar(1);
					mMessage.what = UIHelper.FINGERPRINT_UPIMAGE_SUCCESS;
					Bundle bundle = new Bundle();
					bundle.putByteArray(UIHelper.FINGERPRINT_SOURCE, data);
					mMessage.setData(bundle);
					send();
				}

				@Override
				public void onUpImageFail() {
					Log.i(TAG, "---->setOnUpImageListener onUpImageFail 011");
					mMessage.what = UIHelper.FINGERPRINT_UPIMAGE_FAIL;
					send();
				}
			});

			mValidateFingerprint.setOnGenCharListener(new AsyncFingerprint.OnGenCharListener() {
				@Override
				public void onGenCharSuccess(int bufferId) {
					Log.i(TAG,
							"---->setOnGenCharListener onGenCharSuccess 012 bufferId:"
									+ bufferId);
					mValidateFingerprint.FP_UpChar();
				}

				@Override
				public void onGenCharFail() {
					Log.i(TAG, "---->setOnGenCharListener onGenCharFail 013");
					mMessage.what = UIHelper.FINGERPRINT_SEARCH_FAIL;
					send();
				}
			});
			mValidateFingerprint.setOnUpCharListener(new AsyncFingerprint.OnUpCharListener() {
				@Override
				public void onUpCharSuccess(byte[] model) {
					Log.i(TAG,"setOnUpCharListener onUpCharSuccess");
					if (!isSuccess(model)){
						mMessage.what = UIHelper.FINGERPRINT_SEARCH_FAIL;
						send();
					}
				}

				@Override
				public void onUpCharFail() {
					Log.i(TAG,"setOnUpCharListener onUpCharFail");
					mMessage.what = UIHelper.FINGERPRINT_SEARCH_FAIL;
					send();
				}
			});

		}else {

			mValidateFingerprint.setOnGetImageExListener(new AsyncFingerprint.OnGetImageExListener(){

				@Override
				public void onGetImageExSuccess() {
					Log.i(TAG,
							"---->setOnGetImageExListener onGetImageExSuccess 001");
					if (mIsShowImage) {
						mValidateFingerprint.FP_UpImageEx();//
						Log.i(TAG,
								"---->setOnGetImageExListener onGetImageExSuccess 008");
					} else {
						mValidateFingerprint.FP_GenCharEx(1);
						Log.i(TAG,
								"---->setOnGetImageExListener onGetImageExSuccess 009");
					}
				}

				@Override
				public void onGetImageExFail() {
					Log.i(TAG,
							"---->setOnGetImageExListener onGetImageExFail 002");
					if (!mIsDestory) {
						mValidateFingerprint.FP_GetImageEx();
					}
				}
			});

			mValidateFingerprint.setOnUpImageExListener(new AsyncFingerprint.OnUpImageExListener() {
				@Override
				public void onUpImageExSuccess(byte[] data) {
					Log.i(TAG,
							"---->setOnGetImageExListener onUpImageExSuccess 010");
					Log.i(TAG, "---->setOnUpImageExListener up image data.length="
							+ data.length);
					mValidateFingerprint.FP_GenCharEx(1);
					mMessage.what = UIHelper.FINGERPRINT_UPIMAGE_SUCCESS;
					Bundle bundle = new Bundle();
					bundle.putByteArray(UIHelper.FINGERPRINT_SOURCE, data);
					mMessage.setData(bundle);
					send();
				}

				@Override
				public void onUpImageExFail() {
					Log.i(TAG, "---->setOnGetImageExListener onUpImageExFail 011");
					mMessage.what = UIHelper.FINGERPRINT_UPIMAGE_FAIL;
					send();
				}

			});

			mValidateFingerprint.setOnGenCharExListener(new AsyncFingerprint.OnGenCharExListener() {

				@Override
				public void onGenCharExSuccess(int bufferId) {
					Log.i(TAG,
							"---->setOnGenCharExListener onGenCharExSuccess 012 bufferId:"
									+ bufferId);
					mValidateFingerprint.FP_UpChar();
				}

				@Override
				public void onGenCharExFail() {
					Log.i(TAG, "---->setOnGenCharExListener onGenCharExFail 013");
					mMessage.what = UIHelper.FINGERPRINT_SEARCH_FAIL;
					send();
				}
			});


		}

		// 搜索指纹
		mValidateFingerprint.setOnSearchListener(new AsyncFingerprint.OnSearchListener() {
			@Override
			public void onSearchSuccess(int pageId, int matchScore) {
				Log.i(TAG, "pageId=" + pageId + "    matchScore=" + matchScore);
				mMessage.what = UIHelper.FINGERPRINT_SEARCH_SUCCESS;
				mMessage.arg1 = pageId;
				mMessage.arg2 = SIGNIN_TYPE_FINGER;
				send();
				Log.i(TAG,
						"---->setOnGenCharExListener setOnSearchListener " + 22);
			}

			@Override
			public void onSearchFail() {
				mMessage.what = UIHelper.FINGERPRINT_SEARCH_FAIL;
				send();
				Log.i(TAG, "---->setOnGenCharExListener onSearchFail " + 23);
			}
		});
	}

	private boolean isSuccess(byte[] model){
		if (model == null){
			return false;
		}
		Log.i(TAG,"isSuccess 001 byte length:" + model.length);
		try{
			mFingerBeans = mKjdb.findAll(FingerPrintBean.class);
		}catch (Exception e){
			e.printStackTrace();
		}
		byte[] fpmatch=new byte[model.length];
		System.arraycopy(model, 0, fpmatch, 0, model.length);
		//匹配
		if (mFingerBeans != null && !mFingerBeans.isEmpty()){
			for (FingerPrintBean bean : mFingerBeans){
				if (bean != null && !StringUtils.isEmpty(bean.getFp())) {
					int fingerId = bean.getId();
					Log.i(TAG,"isSuccess 002 fp length:" + bean.getFp().length());
					int ret=FPMatch.getInstance().MatchTemplate(CodecUtils
							.base64DecodeToByte(bean.getFp()),fpmatch);
					Log.i(TAG,"isSuccess fingerId:" + fingerId + ",ret:" + ret);
					if (ret > 80){
						//xTimerStop();
						mMessage.what = UIHelper.FINGERPRINT_SEARCH_SUCCESS;
						mMessage.arg1 = fingerId;
						mMessage.arg2 = SIGNIN_TYPE_FINGER;
						send();
						return true;
					}
				}
			}
		}
		return false;
	}


	/***
	 * 设置是否显示指纹图像
	 */
	public void showImage(boolean isShowImage) {
		this.mIsShowImage = isShowImage;
	}

	/***
	 * 是否有数据返回
	 */
	public void isCallBack(boolean isCallBack) {
		this.mIsCallBack = isCallBack;
	}

	/**
	 * 是否是工作人员，如果非工作人员，则关闭打卡功能，默认false
	 */
	public void isManager(boolean isManager) {
		this.mIsManager = isManager;
	}

	/***
	 * 设置是否注释
	 */
	public void isDestory(boolean isDestory) {
		this.mIsDestory = isDestory;
	}

	public void setFingerPrintReader(AsyncFingerprint fingerprintReader){
		this.mValidateFingerprint = fingerprintReader;
	}

	public void setHandle(Handler handler){
		this.mHandler = handler;
	}

	/***
	 * 执行
	 */
	public void execute() {
		initListener();
		this.mIsDestory = false;
		validateFingerprintSync();
	}

	public void executeAgain(){
		if (mValidateFingerprint != null){
			mValidateFingerprint.FP_GetImage();
		}
	}



	/***
	 * 返回处理结果
	 */
	public void send() {
		if (mIsCallBack) {
			mHandler.sendMessage(mMessage);
			mMessage = new Message();
		}
	}

	/***
	 * 注销
	 */
	public void destory() {
		mIsDestory = true;
	}

	// 录入指纹
	private synchronized void validateFingerprintSync() {
		if (mValidateFingerprint != null) {
			if (AppContext.getInstance().is3GEquipment()) {
				mValidateFingerprint.FP_GetImage();
			} else {
				mValidateFingerprint.FP_GetImageEx();
			}
		}
	}

}
